package com.lzw.common.tool;

import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by 林志伟 on 2017/6/19.
 */
public class CookieTool {
    @Autowired
    private  HttpServletRequest request;
    @Autowired
    private  HttpServletResponse response;

    private int defaultAge=86400;

    public CookieTool(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
    }

    public CookieTool() {
    }

    /**
     * 删除指定的COOKIE
     * @param name
     */
    public void remove(String name){
        Cookie[] cookies = request.getCookies();
        if(null!=cookies){
            for(Cookie cookie : cookies){
                if(cookie.getName().equals(name)){
                    cookie.setValue(null);
                    cookie.setMaxAge(0);// 立即销毁cookie
                    cookie.setPath("/");
                    this.response.addCookie(cookie);
                }
            }

        }
    }

    /**
     * 删除所有的cookie
     */
    public void removeAll(){
        Cookie[] cookies = request.getCookies();
        if(null!=cookies){
            for(Cookie cookie : cookies){
                cookie.setValue(null);
                cookie.setMaxAge(0);// 立即销毁cookie
                cookie.setPath("/");
                this.response.addCookie(cookie);
            }

        }
    }

    /**
     * 添加cookie
     * @param name
     * @param value
     */
    public void add(String name,String value){
        this.add(name,value,this.defaultAge);
    }

    /**
     * 添加cookie
     * @param name
     * @param value
     * @param age
     */
    public void add(String name,String value,int age){
        Cookie cookie = new Cookie(name.trim(), value.trim());
        cookie.setMaxAge(age);// 设置为30min
        cookie.setPath("/");
        System.out.println("已添加===============");
        response.addCookie(cookie);
    }

    /**
     * 获取cookie的值
     * @param name
     * @return
     */
    public String  get(String name){
        Cookie[] cookies = request.getCookies();
        if(null!=cookies){
            for(Cookie cookie : cookies){
                if(cookie.getName().equals(name)){
                    return  cookie.getValue();
                }
            }

        }
        return  null;
    }
}
